<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" v-model="form" ref="crud"
               @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
               @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="warning" size="small" plain icon="el-icon-download" @click="exportBusinessMonth">导出
        </el-button>
      </template>
    </avue-crud>

  </basic-container>
</template>


<script>
import {getList, getDetail, exportBusinessMonth} from "@/api/business/purchaseItem";

export default {
  data() {
    return {
      dateRange: {
        beginTime: "",
        endTime: ""
      },
      monthValue: '',
      search: {
        billYear: [],
        isZk: 1, //否
        isHy: 1, //否
        fileName: '',
      },
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        emptyBtn: false,
        addBtn: false,
        menu: false,
        columnBtn: false,
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        selection: false,
        // formWidth: 'auto',
        //menuWidth: 1,
        column: [
          {
            label: "上报月份",
            prop: "month",
            format: "yyyy-MM",
            valueFormat: "yyyy-MM",
            type: 'month',
            searchSpan: 10,
            searchRange: true,
            search: true,
            searchValue: [],
            searchClearable: false,
          },
          {
            label: "药品流水号",
            prop: "medicineNo",
            type: "input",
            width: 100
          },
          {
            label: "上报机构名称",
            prop: "instName",
            type: "input",
            width: 150,
            overHidden: true,
          },
          {
            label: "通用名",
            prop: "medicineName",
            type: "input",
            width: 150,
          },
          {
            label: "挂网类型",
            prop: "publishType",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=hang_net_type",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            width: 180,
            overHidden: true,
          },
          {
            label: "剂型",
            prop: "shotType",
            type: "input",
          },
          {
            label: "规格",
            prop: "specification",
            type: "input",
          },
          {
            label: "包装",
            prop: "pack",
            type: "input",
          },
          {
            label: "质量类型",
            prop: "qualityType",
            type: "input",
          },
          {
            label: "新版基药属性",
            prop: "baseMedProp",
            type: "input",
            width: 100
          },
          {
            label: "生产企业名称",
            prop: "produceCompanyName",
            type: "input",
            overHidden: true,
            width: 150,
          },
          {
            label: "未按照挂网价格采购是否履行备案手续",
            prop: "fileRecord",
            type: "input",
            width: 150,
            overHidden: true,
          },
          {
            label: "采购数量",
            prop: "amount",
            type: "input",
          },
          {
            label: "实际采购单价（元）",
            prop: "actualPrice",
            type: "input",
            width: 130
          },
          {
            label: "同组别挂网价（元）",
            prop: "minPrice",
            type: "input",
            width: 130
          },
          {
            label: "实际采购总价",
            prop: "sumPrice",
            type: "input",
            width: 120
          },
          {
            label: "备注",
            prop: "remark",
            type: "input",
            width: 150,
          },
          {
            label: "采购单名称",
            prop: "purchaseOrderName",
            type: "input",
            width: 150,
            overHidden: true
          },
          {
            label: "医院名称",
            prop: "hospitalName",
            type: "input",
            width: 150,
            overHidden: true
          },
          {
            label: "省集采网医院账号",
            prop: "hospitalAccount",
            type: "input",
            width: 150,
            overHidden: true
          },
          {
            label: "卫生室名称",
            prop: "clinicName",
            type: "input",
            width: 150,
            overHidden: true
          },
          {
            label: "IS47",
            prop: "is47",
            type: "input",
            width: 150,
            overHidden: true
          },
          {
            label: "配送企业名称",
            prop: "distributionCompanyName",
            type: "input",
            width: 150,
            overHidden: true
          },
          {
            label: "配送企业编号",
            prop: "distributionCompanyNo",
            type: "input",
            width: 150,
            overHidden: true
          },
          {
            label: "采购单提交时间",
            prop: "purchaseOrderTime",
            type: "input",
            width: 120,
            overHidden: true
          },
          {
            label: "采购金额",
            prop: "purchaseAmount",
            type: "input",
            width: 150,
            overHidden: true
          },
          {
            label: "配送时间",
            prop: "deliverTime",
            type: "input",
            width: 120,
            overHidden: true
          },
          {
            label: "配送数量",
            prop: "deliverQuantity",
            type: "input",
            width: 120,
            overHidden: true
          },
          {
            label: "配送金额",
            prop: "deliverAmount",
            type: "input",
            width: 150,
            overHidden: true
          },
          {
            label: "采购单入库时间",
            prop: "purchaseInTime",
            type: "input",
            width: 120,
            overHidden: true
          },
          {
            label: "包装单位入库数量",
            prop: "packageQuantity",
            type: "input",
            width: 120,
            overHidden: true
          },
          {
            label: "制剂单位入库数量",
            prop: "preparationQuantity",
            type: "input",
            width: 120,
            overHidden: true
          },
          {
            label: "入库金额",
            prop: "warehousing_amount",
            type: "input",
            width: 150,
            overHidden: true
          },

        ]
      },
      data: []
    };
  },

  methods: {
    exportBusinessMonth() {
      const {month} = this.query;
      // this.$confirm("确定将当前页面数据导出?", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      // });
      //console.log(month)
      let fileName;
      //console.log(month)
      if (month !== undefined) {
        fileName = '荆州市' + month[0] + '月份至' + month[1] + '月份药品上报目录';
      } else {
        const currentDate = new Date();
        // 获取当前年月份
        const currentYear = currentDate.getFullYear();
        const currentMonth = String(currentDate.getMonth() + 1).padStart(2, '0');
        const currentYearMonth = `${currentYear}-${currentMonth}`;
        // 获取前一个年月份
        const previousDate = new Date(currentYear, currentDate.getMonth() - 1);
        const previousYear = previousDate.getFullYear();
        const previousMonth = String(previousDate.getMonth() + 1).padStart(2, '0');
        const previousYearMonth = `${previousYear}-${previousMonth}`;
        fileName = '荆州市' + previousYearMonth + '月份至' + currentYearMonth + '月份药品上报目录';
      }
      //console.log("123",...this.search)
      var length = this.search.billYear.length;
      if (length > 0) {
        this.search.billYear[length - 1] = month;
      } else {
        this.search.billYear.push(month);
      }

      const searchParams = {...this.search}
      //searchParams.nodeLevel = this.userInfo.loginTeam.nodeLevel;
      //searchParams.parId=this.userInfo.loginTeam.id;
      searchParams.sheetName = fileName;
      this.loading = true;
      exportBusinessMonth(searchParams, month).then((exp) => {
        if (exp.request.response.size > 0) {
          if (exp.status !== 200) {
            this.$message.warning("导出数据异常");
            this.loading = false;
            return;
          }
          const url = window.URL.createObjectURL(exp.request.response)
          const a = document.createElement('a')
          document.body.appendChild(a)
          a.href = url
          a.download = fileName
          a.click()
          window.URL.revokeObjectURL(url)
          this.loading = false;
        } else {
          this.$message.warning('导出失败!')
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    /*    rowSave(row, done, loading) {
          add(row).then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            done();
          }, error => {
            loading();
            window.console.log(error);
          });
        },
        rowUpdate(row, index, done, loading) {
          update(row).then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            done();
          }, error => {
            loading();
            console.log(error);
          });
        },*/
    /*    rowDel(row) {
          this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              return remove(row.id);
            })
            .then(() => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            });
        },
        handleDelete() {
          if (this.selectionList.length === 0) {
            this.$message.warning("请选择至少一条数据");
            return;
          }
          this.$confirm("确定将选择数据删除?", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              return remove(this.ids);
            })
            .then(() => {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.$refs.crud.toggleSelection();
            });
        },*/
    /*beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },*/
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      const date1 = new Date(params.month[0]);
      const date2 = new Date(params.month[1]);
      const yearDiff = date2.getFullYear() - date1.getFullYear();
      const monthDiff = (yearDiff * 12) + (date2.getMonth() - date1.getMonth());

      if (monthDiff >= 12) {
        this.$confirm("时间区间大于一年，数据量过大，拒绝查询", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        });
        done();
      } else {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
      }
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      const {month} = this.query;
      //console.log(month,"1234543")
      let values = {
        ...params,
        ...this.query
      };
      if (month) {
        values = {
          ...values,
          month1: month[0],
          month2: month[1],
        };
        values.month = null;
      }
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    }
  },
  created() {
    const currentDate = new Date();
    const currentYear1 = currentDate.getFullYear();
    const currentMonth2 = String(currentDate.getMonth() + 1).padStart(2, '0');
    this.currentYearMonth = `${currentYear1}-${currentMonth2}`;
    // 获取前一个年月份
    const previousDate = new Date(currentYear1, currentDate.getMonth() - 1);
    const previousYear = previousDate.getFullYear();
    const previousMonth = String(previousDate.getMonth() + 1).padStart(2, '0');
    this.previousYearMonth = `${previousYear}-${previousMonth}`;

    this.findObject(this.option.column, 'month').searchValue = [this.previousYearMonth, this.currentYearMonth];
    this.searchValue = [this.previousYearMonth, this.currentYearMonth];
    this.onLoad(this.page, {month: this.searchValue}); // 在页面加载时调用onLoad方法，并传递初始值
    //console.log(this.searchValue)
  },
  mounted() {
    const currentDate = new Date();
    const currentYear1 = currentDate.getFullYear();
    const currentMonth2 = String(currentDate.getMonth() + 1).padStart(2, '0');
    this.currentYearMonth = `${currentYear1}-${currentMonth2}`;
    // 获取前一个年月份
    const previousDate = new Date(currentYear1, currentDate.getMonth() - 1);
    const previousYear = previousDate.getFullYear();
    const previousMonth = String(previousDate.getMonth() + 1).padStart(2, '0');
    this.previousYearMonth = `${previousYear}-${previousMonth}`;

    this.findObject(this.option.column, 'month').searchValue = [this.previousYearMonth, this.currentYearMonth];

    const currentYear = currentDate.getFullYear();
    const currentMonth = String(currentDate.getMonth() + 1).padStart(2, '0');
    this.searchValue = [`${currentYear}-${currentMonth}`, `${currentYear}-${currentMonth}`];
  },

};
</script>

<style></style>
